import React, { Component } from 'react'
import axios from 'axios'
import { Button, Layout, Table, Modal, Form, Input, Space } from 'antd';
import user_style from './index.module.css'

export default class List extends Component {
  state = {
    users: [],
    columns: [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
      },
      {
        title: '作者',
        dataIndex: ['user', 'name'], // 这里使用嵌套属性
        key: 'username', // 可以使用一个新的 key
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Space size="middle">
            <a onClick={() => this.editUser(record)}>编辑</a>
            <a onClick={() => this.deleteConfirm(record)}>删除</a>
          </Space>
        ),
      }
    ],
    editModalVisible: false, // 编辑模态框的可见性
    editedUser: {}, // 正在编辑的用户

    addModalVisible: false, // 模态框的可见性
    addedUser: {}, // 正在添加的用户
  }

  deleteConfirm = (user) => {
    Modal.confirm({
      title: '确认删除',
      content: '您确定要删除该帖子吗？',
      onOk: () => {
        // 调用删除用户的方法
        this.deleteUser(user);
      },
    });
  }
  addUser = () => {
    this.setState({
      addModalVisible: true,
    });
  }
  handleAddModalOk = () => {
    // 数据保存
    // 更新用户信息
    let _this = this;
    axios.post('http://localhost:3000/posts', this.state.addedUser).then(
      res => {
        console.log('res', res)
        if (res.status === 200) {
          // 成功添加用户后，刷新用户列表
          _this.getListData();
        }
      },
      err => {
        console.log('err', err)
      }
    )
    this.setState({
      addModalVisible: false,
      addedUser: {},
    });
  }

  handleAddModalCancel = () => {
    // 关闭模态框，不保存编辑后的数据
    this.setState({
      addModalVisible: false,
      addedUser: {},
    });
  }
  // 删除用户的方法
  deleteUser = (user) => {
    let _this = this;
    console.log('user', user)
    axios.delete(`http://localhost:3000/posts/${user.id}`).then(
      res => {
        console.log('res', res)
        if (res.status === 200) {
          // 刷新用户列表
          _this.getListData();
        }
      },
      err => {
        console.log('err', err)
      }
    )
  }

  editUser = (user) => {
    this.setState({
      editedUser: user,
      editModalVisible: true,
    });
  }
  handleEditModalOk = () => {
    let _this = this;
    axios.put(`http://localhost:3000/posts/${this.state.editedUser.id}`, this.state.editedUser).then(
      res => {
        console.log('res', res)
        if (res.status === 200) {
          // 成功添加用户后，刷新用户列表
          _this.getListData();
        }
      },
      err => {
        console.log('err', err)
      }
    )
    
    this.setState({
      editModalVisible: false,
      editedUser: {},
    });
  }

  handleEditModalCancel = () => {
    // 关闭模态框，不保存编辑后的数据
    this.setState({
      editModalVisible: false,
      editedUser: {},
    });
  }
  // 编辑表单字段的 onChange 处理程序
  handleNameChange = (e) => {
    const editedUser = { ...this.state.editedUser };
    editedUser.title = e.target.value;
    this.setState({ editedUser });
  }

  handleEmailChange = (e) => {
    const editedUser = { ...this.state.editedUser };
    editedUser.content = e.target.value;
    this.setState({ editedUser });
  }
  // 添加用户模态框字段的 onChange 处理程序
  handleAddedNameChange = (e) => {
    const addedUser = { ...this.state.addedUser };
    addedUser.title = e.target.value;
    this.setState({ addedUser });
  }

  handleAddedEmailChange = (e) => {
    const addedUser = { ...this.state.addedUser };
    addedUser.content = e.target.value;
    this.setState({ addedUser });
  }
  getListData = () => {
    let _this = this;
    axios.get('http://localhost:3000/posts').then(
      res => {
        console.log('res', res)
        if (res.status === 200) {
          let users = res.data;
          console.log("_this", _this)
          console.log('users', users)
          _this.setState({ users: users }, () => {
            console.log("_this.state.users", _this.state.users)
          })
        }
      },
      err => {
        console.log('err', err)
      }
    )
  }
  componentDidMount() {
    this.getListData()
  }
  render() {
    return (
      <div >
        <div className={user_style.title_wrap}>
          <h3>帖子列表</h3>
          <Button onClick={this.addUser} type="primary">添加帖子</Button>
        </div>
        <Table dataSource={this.state.users} columns={this.state.columns} />
        <Modal
          title="编辑帖子"
          open={this.state.editModalVisible}
          onOk={this.handleEditModalOk}
          onCancel={this.handleEditModalCancel}
        >
          <Form>
            <Form.Item label="标题">
              <Input
                value={this.state.editedUser.title}
                onChange={this.handleNameChange}
              />
            </Form.Item>
            <Form.Item label="内容">
              <Input
                value={this.state.editedUser.content}
                onChange={this.handleEmailChange}
              />
            </Form.Item>
            {/* 添加其他编辑字段 */}
          </Form>
        </Modal>
        <Modal
          title="添加帖子"
          open={this.state.addModalVisible}
          onOk={this.handleAddModalOk}
          onCancel={this.handleAddModalCancel}
        >
          <Form>
            <Form.Item label="标题">
              <Input
                value={this.state.addedUser.title}
                onChange={this.handleAddedNameChange}
              />
            </Form.Item>
            <Form.Item label="内容">
              <Input
                value={this.state.addedUser.content}
                onChange={this.handleAddedEmailChange}
              />
            </Form.Item>
            {/* 添加其他编辑字段 */}
          </Form>
        </Modal>
      </div>

    )
  }
}
